console.log(localStorage["showBanner"]);

var config = {
	showBanner : true,
	hideTime : 5,
	lastState : 0,
	save : function() {
		localStorage["showBanner"] = this.showBanner;
		localStorage["hideTime"] = this.hideTime;
	}
}

if (localStorage["showBanner"] != undefined) {
	config.showBanner = new Boolean(localStorage["showBanner"]);
}

if (localStorage["hideTime"] != undefined) {
	config.hideTime = parseInt(localStorage["hideTime"]);
}

var cbaTabs = [];

function CbaTab(tabId) {
	this.state = "none";
	this.tabId = tabId;
	this.cbaCount = 0;
	return this;
}

function renderCount(count) {
	if (count > 1000) {
		return Math.floor(count / 1000) + "K";
	} else {
		return count + "";
	}
}

CbaTab.prototype.refresh = function(count, callback, showBanner) {
	var me = this;

	chrome.tabs.get(this.tabId, function(tab) {
		var encoded = encodeURIComponent(tab.url);

		var ajxUrl = "http://cba-page.appspot.com/count?url=" + encoded;
		if (count) {
			ajxUrl += "&count=true";
		}
		console.log("쿼리를 보내는 중: " + ajxUrl);

		$.ajax({
			url : ajxUrl,
			success : function(data) {
				console.log("수신: " + data);
				var result = eval("(" + data + ")");
				me.lastState = result.state;
				
				if (result.count > 0 && showBanner) {
					chrome.tabs.insertCSS(tab.tabId, {
						file : "resource/overlay.css"
					});
					chrome.tabs.executeScript(tab.tabId, {
						file : "overlay.js",
						allFrames : false
					});
					console.log("오버레이 스크립트 수행 요청");
				}

				me.cbaCount = result.count;
				var badge = (result.count == 0) ? ""
						: renderCount(result.count);
				var title = (result.count == 0) ? "아무도 이 페이지를 씨바스러워 하지 않음."
						: result.count + " 명의 사람이 이 페이지를 씨바스러워 함.";
				chrome.browserAction.setBadgeText({
					"tabId" : me.tabId,
					"text" : badge
				});
				chrome.browserAction.setTitle({
					"tabId" : me.tabId,
					"title" : title
				});
				me.state = "done";
				if (callback) {
					callback(result);
				}
			}
		});
		me.state = "loading";
	});
};

function ensureCbaTab(tabId) {
	var result = cbaTabs[tabId];

	if (!result) {
		cbaTabs[tabId] = result = new CbaTab(tabId);
	}

	return result;
}

function removeCbaTab(tabId) {
	cbaTabs[tabId] = undefined;
}

chrome.tabs.onUpdated.addListener(handleTabUpdate);
chrome.tabs.onRemoved.addListener(handleTablRemoved);

function handleTabUpdate(tabId, changeInfo, tab) {
	var ct = ensureCbaTab(tabId);
	if (changeInfo.status == "loading") {
		ct.state = "loading";
		console.log(config.showBanner);
		ct.refresh(false, null, config.showBanner);
	}
}

function handleTablRemoved(tabId, removeInfo) {
	removeCbaTab(tabId);
}

chrome.extension.onRequest.addListener(function(req, sender, sendResponse) {
	if (sender.tab && req == "count") {
		var ctab = ensureCbaTab(sender.tab.id);
		console.log(ctab + "탭의 컨텐츠 스크립트에서 요청을 받음");
		sendResponse({
			"count" : ctab.cbaCount,
			"config" : config
		});
	}

	else if (req == "options") {
		showOptionPage();
	}

	else if (req == "cba") {
		chrome.tabs.getSelected(null, function(tab) {
			var ctab = ensureCbaTab(tab.id);
			ensureCbaTab(tab.id).refresh(true, function() {
				var msg = {
					"count" : ctab.cbaCount,
					"config" : config
				};
				if(ctab.lastState == 1){
					msg.error = "이미 씨바를 날렸습니다.";
				}
				sendResponse(msg);
			});
		});
	}
});

function showOptionPage() {
	var url = chrome.extension.getURL("options.html");
	chrome.tabs.create({
		"url" : url
	});

}